import { _decorator, AudioClip, AudioSource, Component, director, log, Node, resources } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {

    private static _instance: AudioManager = null;
    public static get Instance(): AudioManager {
        if (!this._instance) {
            this._instance = new AudioManager();
        }
        return this._instance;
    }

    static AudioBgm: Node = null;
    static AudioSound: Node = null;

    static IsPlayAudio: boolean = true;

    start() {

    }

    update(deltaTime: number) {

    }

    playBGM(path: string) {
        if (!AudioManager.IsPlayAudio) {
            return;
        }
        if (AudioManager.AudioBgm) {
            resources.load(path, AudioClip, (err, clip) => {
                AudioManager.AudioBgm.getComponent(AudioSource).clip = clip;
                AudioManager.AudioBgm.getComponent(AudioSource).play();
            })
        }
        else {
            let bgmNode = new Node();
            bgmNode.addComponent(AudioSource);
            AudioManager.AudioBgm = bgmNode;
            resources.load(path, AudioClip, (err, clip) => {
                let audioSource = bgmNode.getComponent(AudioSource);
                audioSource.clip = clip;
                audioSource.loop = true;
                audioSource.playOnAwake = false;
                audioSource.play();
            })
        }
    }

    playSound(path: string, loop: boolean = false) {
        if (!AudioManager.IsPlayAudio) {
            return;
        }
        if (AudioManager.AudioSound) {
            resources.load(path, AudioClip, (err, clip) => {
                AudioManager.AudioSound.getComponent(AudioSource).clip = clip;
                AudioManager.AudioSound.getComponent(AudioSource).play();
            })
        }
        else {
            let soundNode = new Node();
            soundNode.addComponent(AudioSource);
            AudioManager.AudioSound = soundNode;
            resources.load(path, AudioClip, (err, clip) => {
                let audioSource = soundNode.getComponent(AudioSource);
                audioSource.clip = clip;
                audioSource.loop = loop;
                audioSource.playOnAwake = false;
                audioSource.play();
            })
        }
    }

    stopAudioPlay() {
        AudioManager.IsPlayAudio = false;
        AudioManager.AudioBgm.getComponent(AudioSource).stop();
        if (AudioManager.AudioSound) {
            AudioManager.AudioSound.getComponent(AudioSource).stop();
        }

    }
    openAudioPlay() {
        AudioManager.IsPlayAudio = true;
        AudioManager.AudioBgm.getComponent(AudioSource).play();
    }
}


